package com.lc.demo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lc.demo.bean.*;
import com.lc.demo.result.ResponseMessage;
import com.lc.demo.service.ClassGradleService;
import com.lc.demo.service.ScoreService;
import com.lc.demo.service.StudentService;
import com.lc.demo.service.SubjectService;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName StudentController
 * @Deacription TODO
 * @Author jinshuhan
 * @Version 1.0
 **/


@CrossOrigin
@RestController
@RequestMapping("/stu")
public class StudentController {

    @Autowired
    private StudentService studentService;


    @Autowired
    private ScoreService scoreService;

    @Autowired
    private ClassGradleService classGradleService;

    //登陆接口
    @PostMapping(value = "/login")
    public ResponseMessage login(@RequestBody Student student) {
        Student stu = studentService.login(student.getUsername(), student.getPassword());
        if (stu != null) {
            return ResponseMessage.successWithMessage(student.getUsername());
        } else {
            return ResponseMessage.errorWithMessage("用户名或密码错误");
        }
    }


    //查询成绩列表接口
    @PostMapping(value = "/getScoreList")
    public ResponseMessage getScoreList(@RequestBody Student student) {
        // String username = (String) session.getAttribute("loginUser");

        int pageNum = 1;
        int pageSize = 10;
        if (student.getPageNum() != null) {
            pageNum = student.getPageNum();
        }
        if (student.getPageSize() != null) {
            pageSize = student.getPageSize();
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Score> scoreList = studentService.getScoreListByUsername(student.getUsername());
        PageInfo<Score> page = new PageInfo<>(scoreList);


        return ResponseMessage.successWithData(page);
    }

    //成绩复核接口
    @PostMapping(value = "/review")
    public ResponseMessage review(@RequestBody Score score) {
        // String username = (String) session.getAttribute("loginUser");

        scoreService.review(score);
        return ResponseMessage.success();
    }


    //成绩分析接口
    @PostMapping(value = "/analyse")
    public ResponseMessage analyse(@RequestBody Student student) {
        Student student1 = studentService.analyse(student);
        return ResponseMessage.successWithData(student1);
    }


    @Autowired
    private SubjectService subjectService;

    //生成word文档 存到本地
    @PostMapping(value = "/export")
    public ResponseMessage export(@RequestBody Student student) {

        //查询出所需数据
        //查询出学生姓名
        Student studentQuery = studentService.selectByUsername(student.getUsername());
        //查询出学生的成绩
        List<Score> scoreList = scoreService.selectScoreListByUsername(student.getUsername());
        //生成word文档
        List<ArrayList<String>> testList = new ArrayList<>();
        for (Score score : scoreList) {
            ArrayList<String> strings = new ArrayList<>();
            strings.add(score.getSubname());
            Subject subject = subjectService.selectSubjectByName(score.getSubname());
            strings.add(subject.getTerm());
            strings.add(score.getScore() + "");
            testList.add(strings);
        }
        List<Map<String, String>> mapList = new ArrayList<>();
        Map<String, String> testMap = new HashMap<String, String>();
        testMap.put("name", studentQuery.getName());
        testMap.put("username", studentQuery.getUsername());
        testMap.put("courts", studentQuery.getCourts());
        testMap.put("major", studentQuery.getMajor());
        //查询班级名称
        String className = classGradleService.getClassNameById(studentQuery.getClassid());


        testMap.put("classname", className);

        mapList.add(testMap);
        changWord("D://word/wordinput.docx", "D://word/wordoutput.docx", mapList, testList);


        return ResponseMessage.success();
    }

    /**
     * 根据模板生成新word文档
     * 判断表格是需要替换还是需要插入，判断逻辑有$为替换，表格无$为插入
     *
     * @param inputUrl  模板存放地址
     * @param outputUrl 新文档存放地址
     * @param mapList   需要替换的信息集合
     * @param tableList 需要插入的表格信息集合
     */
    public boolean changWord(String inputUrl, String outputUrl,
                             List<Map<String, String>> mapList, List<ArrayList<String>> tableList) {
        //模板转换默认成功
        boolean changeFlag = true;
        try {
            for (Map<String, String> textMap : mapList) {
                //获取docx解析对象
                XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
                //解析替换文本段落对象
                changeText(document, textMap);
                //解析替换表格对象
                changeTable(document, textMap, tableList);
                //生成新的word
                File file = new File(outputUrl);
                FileOutputStream stream = new FileOutputStream(file);
                document.write(stream);
                stream.close();
                System.out.println("成功生成！");
            }

        } catch (IOException e) {
            e.printStackTrace();
            changeFlag = false;
        }

        return changeFlag;

    }

    /**
     * 替换段落文本
     *
     * @param document docx解析对象
     * @param textMap  需要替换的信息集合
     */
    public void changeText(XWPFDocument document, Map<String, String> textMap) {
        //获取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            //判断此段落时候需要进行替换
            String text = paragraph.getText();
            if (checkText(text)) {
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String textValue = changeValue(run.toString(), textMap);
                    run.setText(textValue, 0);
                }
            }
        }
    }

    /**
     * 替换表格对象方法
     *
     * @param document  docx解析对象
     * @param textMap   需要替换的信息集合
     * @param tableList 需要插入的表格信息集合
     */
    public void changeTable(XWPFDocument document, Map<String, String> textMap,
                            List<ArrayList<String>> tableList) {
        //获取表格对象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            //只处理行数大于等于2的表格，且不循环表头
            XWPFTable table = tables.get(i);
            if (table.getRows().size() > 1) {
                //判断表格是需要替换还是需要插入，判断逻辑有$为替换，表格无$为插入
                if (checkText(table.getText())) {
                    List<XWPFTableRow> rows = table.getRows();
                    //遍历表格,并替换模板
                    eachTable(rows, textMap);
                } else {
//                  System.out.println("插入"+table.getText());
                    insertTable(table, tableList);
                }
            }
        }
    }


    /**
     * 遍历表格
     *
     * @param rows    表格行对象
     * @param textMap 需要替换的信息集合
     */
    public void eachTable(List<XWPFTableRow> rows, Map<String, String> textMap) {
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判断单元格是否需要替换
                if (checkText(cell.getText())) {
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            run.setText(changeValue(run.toString(), textMap), 0);
                        }
                    }
                }
            }
        }
    }

    /**
     * 为表格插入数据，行数不够添加新行
     *
     * @param table     需要插入数据的表格
     * @param tableList 插入数据集合
     */
    public void insertTable(XWPFTable table, List<ArrayList<String>> tableList) {
        //创建行,根据需要插入的数据添加新行，不处理表头
        for (int i = 1; i < tableList.size(); i++) {
            XWPFTableRow row = table.createRow();
        }
        //遍历表格插入数据
        List<XWPFTableRow> rows = table.getRows();
        for (int i = 1; i < rows.size(); i++) {
            XWPFTableRow newRow = table.getRow(i);
            List<XWPFTableCell> cells = newRow.getTableCells();
            for (int j = 0; j < cells.size(); j++) {
                XWPFTableCell cell = cells.get(j);
                cell.setText(tableList.get(i - 1).get(j));
            }
        }
    }

    /**
     * 判断文本中时候包含$
     *
     * @param text 文本
     * @return 包含返回true, 不包含返回false
     */
    public boolean checkText(String text) {
        boolean check = false;
        if (text.contains("$")) {
            check = true;
        }
        return check;
    }

    /**
     * 匹配传入信息集合与模板
     *
     * @param value   模板需要替换的区域
     * @param textMap 传入信息集合
     * @return 模板需要替换区域信息集合对应值
     */
    public String changeValue(String value, Map<String, String> textMap) {
        Set<Map.Entry<String, String>> textSets = textMap.entrySet();
        for (Map.Entry<String, String> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = "${" + textSet.getKey() + "}";
            if (value.contains(key)) {
                // value = textSet.getValue();//全部参数替换
                value = value.replace(key, textSet.getValue());//仅替换参数
            }
        }
        //模板未匹配到区域替换为空
        if (checkText(value)) {
            value = "";
        }
        return value;
    }
   /* //批量生成word  写个循环就行了
    public static void main(String[] args) {
        //模板文件地址
        String inputUrl = "D://develop/javatoword/wordinput.docx";
        //新生产的模板文件
        String outputUrl = "D://develop/javatoword/wordoutput.docx";
      *//*  //模板文件地址
        String inputUrl = "classpath:/word/wordinput.docx";
        //新生产的模板文件
//        String outputUrl = "D://develop/javatoword/wordoutput.docx";
        String outputUrl = "classpath:/word/wordoutput.docx";*//*

        List<Map<String, String>> mapList=new ArrayList<>();

        Map<String, String> testMap = new HashMap<String, String>();
        testMap.put("name", "小明");
        testMap.put("sex", "男");
        testMap.put("nling", "18");
        testMap.put("address", "北京市");
        testMap.put("neirong", "好的内容");
        testMap.put("address", "软件园");
        testMap.put("xuehao", "88888888");

        mapList.add(testMap);

        List<ArrayList<String>> testList = new ArrayList<>();
        ArrayList<String> strings = new ArrayList<>();
        strings.add("1");
        strings.add("2密码");
        strings.add("2B");
        strings.add("基金C");
        testList.add(strings);
        ArrayList<String> strings2 = new ArrayList<>();
        strings2.add("3");
        strings2.add("3看看");
        strings2.add("3B");
        strings2.add("基看C");
        testList.add(strings2);
       *//* testList.add(new String[]{"2","2密码","2B","基金C"});
        testList.add(new String[]{"3","3看看","3B","基看C"});
        testList.add(new String[]{"4","4累了","4B","4谁说的"});*//*
        JavaToWord.changWord(inputUrl, outputUrl, mapList,testList);
    }*/




    /*  @PostMapping(value = "/stu/login")
  public String login(@RequestParam("username") String username,
                      @RequestParam("password") String password, Map<String, Object> map, HttpSession session) {
      Student stu = studentService.login(username, password);
      if (stu != null) {
          session.setAttribute("loginUser", username);
          return "redirect:/stumain.html";
      } else {
          map.put("msg", "用户名或密码错误");
          return "login";
      }
  }*/
    /*//返回首页
    @GetMapping(value = "/stu/toindex")
    public String toindex() {
        return "redirect:/stumain.html";
    }


    //返回学生信息修改页面
    @GetMapping(value = "/stu/toUpdateMsgPage")
    public String toUpdateMsgPage(HttpSession httpSession, Model model) {

        Student stu = studentService.selectById((String) httpSession.getAttribute("loginUser"));
        List<Classes> classes = classService.getAllClass();
        model.addAttribute("stu", stu);
        model.addAttribute("classes", classes);
        return "stu/updateStu";
    }

    //更新学生信息操作
    @PutMapping(value = "/stu/updateStuMsg")
    public String updateStuMsg(@Valid Student student, BindingResult bindingResult, Model model, HttpSession httpSession) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<MyError> errmsg = new ArrayList<>();
        List<Classes> classes = classService.getAllClass();
        if (allErrors.size() == 0) {
            Student studentInit = studentService.selectById((String) httpSession.getAttribute("loginUser"));
            student.setStuId(studentInit.getStuId());
            student.setStuName(studentInit.getStuName());
            student.setStuClass(studentInit.getStuClass());
            student.setStuSex(studentInit.getStuSex());

            studentService.deleStu(studentInit.getStuId());
            studentService.addStudentHavePass(student);
            return "redirect:/updateSucc.html";
        } else {
            for (ObjectError error : allErrors) {
                errmsg.add(new MyError(error.getDefaultMessage()));
            }
            model.addAttribute("errors", errmsg);
            model.addAttribute("stu", student);
            model.addAttribute("classes", classes);
            return "stu/updateStu";
        }
    }

    //返回学生成绩首页
    @GetMapping(value = "/stu/toresdmin/{pn}")
    public String toresdmin(@PathVariable("pn") Integer pn, Model model, HttpSession httpSession) {
        PageHelper.startPage(pn, 9);
        List<Resultss> resultsses = resultssService.selectByStuId((String) httpSession.getAttribute("loginUser"));
        PageInfo<Resultss> page = new PageInfo<Resultss>(resultsses, 5);
        model.addAttribute("pageInfo", page);
        return "stu/resultlist";
    }

    //根据学期查询成绩
    @GetMapping(value = "/stu/selectResByTerm/{pn}")
    public String selectResByTerm(@PathVariable("pn") Integer pn, @Param("resTerm") String resTerm, Model model, HttpSession httpSession) {
        PageHelper.startPage(pn, 9);
        List<Resultss> resultsses = resultssService.selectByStuIdAndResTerm((String) httpSession.getAttribute("loginUser"), resTerm);
        PageInfo<Resultss> page = new PageInfo<Resultss>(resultsses, 5);
        model.addAttribute("pageInfo", page);
        model.addAttribute("resTerm", resTerm);
        return "stu/reslistbyterm";
    }*/
}
